<template>
  <div class="dashboard-container">
    <!-- 底部 Tabbar 区域 -->
    <van-tabbar v-model="activeTab">
      <van-tabbar-item name="home" icon="home-o">首页</van-tabbar-item>
      <van-tabbar-item name="mine" icon="user-o">我的</van-tabbar-item>
    </van-tabbar>

    <!-- 首页内容 -->
    <template v-if="activeTab === 'home'">
      <!-- 总控制台区域 -->
      <div class="console-panel">
        <div class="panel-header">
          <van-button 
            icon="arrow-left" 
            class="back-btn"
            @click="goToLogin"
          />
          <h2 class="panel-title">总控制台</h2>
          <div class="notification">
            <van-badge dot>
              <van-icon name="bell" size="22" />
            </van-badge>
          </div>
        </div>

        <!-- 状态信息 -->
        <van-cell-group class="status-group">
          <van-cell>
            <template #icon>
              <img src="../../assets/numCon.png" alt="已连接车辆图标" class="custom-icon" />
            </template>
            <template #title>
              <div class="status-item">
                <span class="status-label">已连接充电桩车辆数：</span>
                <span class="status-value">{{ chargingData.connectedVeh }}/{{ chargingData.totalVeh }}</span>
              </div>
            </template>
          </van-cell>

          <van-cell>
            <template #icon>
              <img src="../../assets/currentState.png" alt="当前状态图标" class="custom-icon" />
            </template>
            <template #title>
              <div class="status-item">
                <span class="status-label">当前状态：</span>
                <span class="status-value" :class="getStatusClass(chargingData.fleetChargeStatus)">
                  {{ getStatusText(chargingData.fleetChargeStatus) }}
                </span>
              </div>
            </template>
          </van-cell>

          <van-cell @click="showChargeDialog = true" class="clickable-cell">
            <template #icon>
              <img src="../../assets/chargingTime.png" alt="预约时间图标" class="custom-icon" />
            </template>
            <template #title>
              <div class="status-item">
                <span class="status-label">预约充电时间：</span>
                <span class="status-value">{{ chargingData.scheduledTime || '--:--' }}</span>
                <img src="../../assets/invertedTriangleIcon.png" alt="倒三角图标" class="triangle-icon" />
              </div>
            </template>
          </van-cell>

          <van-cell @click="showChargeDialog = true" class="clickable-cell">
            <template #icon>
              <img src="../../assets/chargingTarget.png" alt="充电目标图标" class="custom-icon" />
            </template>
            <template #title>
              <div class="status-item">
                <span class="status-label">充电目标：</span>
                <span class="status-value">{{ chargingData.targetSoc || '--' }}%</span>
                <img src="../../assets/invertedTriangleIcon.png" alt="倒三角图标" class="triangle-icon" />
              </div>
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <!-- 车辆信息区域 -->
      <div class="vehicle-section">
        <div class="connected-wrapper">
          <div class="connection-status">已连接</div>
          <div class="bottom-line"></div>
          <div class="inverted-triangle">
            <img src="../../assets/invertedTriangleIcon1.png" alt="倒三角图片" class="triangle-img" />
          </div>
        </div>
        <div class="vehicle-cards">
          <ChargingCard 
            v-for="(vehicle, index) in vehicleList" 
            :key="vehicle.vin"  
            :vin="vehicle.vin"
            :charge-status="vehicle.chargeStatus"
            :connector-id="vehicle.connectorId"
            :start-time="formatTime(vehicle.startTime)"
            :schedule-time="vehicle.chargeStatus === 0 ? vehicle.scheduledTime : ''"
            :charging-duration="formatDuration(vehicle.chargeElapsedTime)"
            :charge-amount="vehicle.chargeKwh || '0'"
            :current-soc="vehicle.currentSoc"
            :target-soc="vehicle.targetSoc"
            :real-time-status="vehicle.chargeStatus === 1 ? getRealTimeStatus(vehicle) : ''"
            :end-time="formatTime(vehicle.endTime)"
            :stop-reason="vehicle.chargeStatus === 255 ? vehicle.failReason : ''"
            @instant-charge="() => startCharging(index)"
          />
        </div>
      </div>

      <!-- 预约充电弹框组件 -->
      <ChargeDialog 
        v-model:show="showChargeDialog" 
        @confirm="confirmCharge"
      />

      <!-- 确认弹框组件 -->
      <van-dialog
        v-model:show="showConfirmDialog"
        :show-confirm-button="false"
        :show-cancel-button="false"
        class="confirm-dialog"
      >
        <div class="confirm-content">
          <div class="confirm-header">
            <h3 class="confirm-title">温馨提示</h3>
          </div>
          <div class="confirm-body">
            <p>当前调度正在充电中，本次修改将在<br>下一次调度执行时开启。是否确定开启?</p>
            <p class="confirm-time">{{ pendingChargeSettings?.time || '02:00' }}</p>
          </div>
          <div class="confirm-footer">
            <van-button class="cancel-btn" @click="cancelModification">取消</van-button>
            <van-button type="primary" class="confirm-btn" @click="confirmModification">确定</van-button>
          </div>
        </div>
      </van-dialog>
    </template>

    <!-- 我的页面 -->
    <template v-else-if="activeTab === 'mine'">
      <MyPage />
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onActivated } from 'vue';
import { 
  Cell, CellGroup, Icon, Badge, Tabbar, TabbarItem, Toast, Dialog, Button 
} from 'vant';
import ChargingCard from '@/components/ChargingCard.vue';
import MyPage from './myPage.vue';
import ChargeDialog from '@/components/ChargeDialog.vue';
import { instantCharging, getTotalControlInfo, getChargingVehInfo } from '@/api/api';
import { useRoute } from 'vue-router';
import { useRouter } from 'vue-router';
import { showToast } from 'vant'; 

const route = useRoute();
const router = useRouter(); 

// 车辆数据列表
const vehicleList = ref([]);

// 控制台数据
const chargingData = ref({
  connectedVeh: 0,
  totalVeh: 0,
  fleetChargeStatus: 0,
  scheduledTime: '',
  targetSoc: 0
});

// 弹窗状态
const showChargeDialog = ref(false);
const showConfirmDialog = ref(false);
const pendingChargeSettings = ref(null);

// Tabbar 控制
const activeTab = ref('home');

// 监听 activeTab 变化
watch(activeTab, (newTab, oldTab) => {
  if (newTab === 'home' && oldTab === 'mine') {
    // 从"我的"切换回"首页"时重新加载数据
    loadData();
  }
});

// 状态转换方法
const getStatusText = (status) => {
  switch(status) {
    case 0: return '未开启';
    case 1: return '充电中';
    case 2: return '已结束';
    case 3: return '未连接';
    case 255: return '故障';
    default: return '未知状态';
  }
};

// 状态颜色类
const getStatusClass = (status) => {
  switch(status) {
    case 0: return 'status-not-started';
    case 1: return 'status-charging';
    case 2: return 'status-finished';
    case 3: return 'status-not-started';
    case 255: return 'status-error';
    default: return '';
  }
};

// 获取实时状态文本
const getRealTimeStatus = (vehicle) => {
  return '680kw 5.5A';
};

// 格式化时间显示
// 格式化时间显示（只保留时分）
const formatTime = (timeString) => {
    // 非字符串或空值返回空（或根据需求改默认提示）
    if (!timeString || typeof timeString!== 'string') { 
        return ''; 
    }
    // 直接返回传入的时间字符串，也可按需截取，比如取前 19 位（即 yyyy-mm-dd hh:mm:ss 长度）
    // 若时间字符串是标准的 "yyyy-mm-dd hh:mm:ss" 格式，想确保取到这部分，用 slice
    return timeString.slice(0, 19); 
};

// 格式化充电时长
const formatDuration = (minutes) => {
  if (minutes === null || minutes === undefined || isNaN(minutes) || minutes < 0) {
    return '未开始';
  }
  
  const totalMinutes = Math.floor(minutes);
  const hours = Math.floor(totalMinutes / 60);
  const remainingMins = totalMinutes % 60;
  
  if (hours > 0) {
    return remainingMins > 0 
      ? `${hours}小时${remainingMins}分钟` 
      : `${hours}小时`;
  } else {
    return `${remainingMins}分钟`;
  }
};

// 预约充电确认
const confirmCharge = async (data) => {
  if (chargingData.value.fleetChargeStatus === 1) {
    pendingChargeSettings.value = data;
    showConfirmDialog.value = true;
  } else {
    applyChargeSettings(data);
  }
};

// 应用充电设置
const applyChargeSettings = (data) => {
  chargingData.value.scheduledTime = data.time;
  chargingData.value.targetSoc = data.target;
  
  vehicleList.value = vehicleList.value.map(vehicle => ({
    ...vehicle,
    targetSoc: data.target,
    scheduledTime: vehicle.chargeStatus === 0 ? data.time : vehicle.scheduledTime
  }));
  
  showChargeDialog.value = false;
};

// 确认修改
const confirmModification = () => {
  if (pendingChargeSettings.value) {
    applyChargeSettings(pendingChargeSettings.value);
    pendingChargeSettings.value = null;
  }
  showConfirmDialog.value = false;
  showToast({
        message: '调度成功',
       type: 'success' // 绿色主题
      });
};

// 取消修改
const cancelModification = () => {
  pendingChargeSettings.value = null;
  showConfirmDialog.value = false;
};

const goToLogin = () => {
  router.push('/');
};

// 即刻充电
const startCharging = async (index) => {
  console.log(11);
  const vehicle = vehicleList.value[index];
  
  try {
    // Toast.loading({ message: '启动充电中...', duration: 0 });
    const response = await instantCharging({
      vin: vehicle.vin,
      connectorId: vehicle.connectorId
    });

    if (response.code === 200) {
      vehicleList.value[index] = {
        ...vehicle,
        chargeStatus: 1,
        startTime: new Date().toISOString(),
        chargeElapsedTime: 0,
        chargeKwh: '0',
        failReason: null,
        scheduledTime: null
      };
      
      showToast({
       message: `车辆 ${vehicle.vin} 开始充电`,
       type: 'success' // 绿色主题
      });
      updateConsoleData();
      // Toast.success(`车辆 ${vehicle.vin} 开始充电`);
    } else {
      Toast.fail(response.message || '启动充电失败');
    }
  } catch (err) {
    console.error('充电失败:', err);
  } finally {
    Toast.clear();
  }
};

// 更新控制台数据
const updateConsoleData = () => {
  const connectedCount = vehicleList.value.filter(
    v => v.chargeStatus === 1 || v.chargeStatus === 2
  ).length;
  
  const totalCount = vehicleList.value.length;
  
  let fleetStatus = 0;
  if (vehicleList.value.some(v => v.chargeStatus === 1)) {
    fleetStatus = 1;
  } else if (vehicleList.value.every(v => v.chargeStatus === 2)) {
    fleetStatus = 2;
  } else if (vehicleList.value.some(v => v.chargeStatus === 255)) {
    fleetStatus = 255;
  }
  
  chargingData.value = {
    ...chargingData.value,
    connectedVeh: connectedCount,
    totalVeh: totalCount,
    fleetChargeStatus: fleetStatus
  };
};

// 从接口获取并同步控制台数据
const fetchConsoleData = async () => {
  try {    
    const response = await getTotalControlInfo();
    if (response.code === 200) {
      const data = response.data;
      chargingData.value = {
        connectedVeh: data.connectedVeh || 0,
        totalVeh: data.totalVeh || 0,
        fleetChargeStatus: data.fleetChargeStatus || 0,
        scheduledTime: data.scheduledTime || '--:--',
        targetSoc: data.targetSoc || 0
      };
    } else {
      Toast.fail(response.message || '获取控制台数据失败');
    }
  } catch (err) {
    console.error('控制台接口调用失败:', err);
  }
};

// 从接口获取车辆列表数据
const fetchVehicleList = async () => {
  try {
    const response = await getChargingVehInfo();
    if (response.code === 200) {
      vehicleList.value = response.data || [];
      updateConsoleData();
    } else {
      Toast.fail(response.message || '获取车辆数据失败');
    }
  } catch (err) {
    console.error('车辆列表接口调用失败:', err);
    Toast.fail('获取车辆数据失败');
  }
};

// 页面加载时执行接口请求
const loadData = () => {
  fetchConsoleData();
  fetchVehicleList();
};

// 组件挂载时加载数据
onMounted(() => {
  loadData();
});

// 从缓存激活时重新加载
onActivated(() => {
  if (activeTab.value === 'home') {
    loadData();
  }
});
</script>

<style scoped>
/* 状态颜色定义 */
.status-not-started { color: #999; }
.status-charging { color: #07C160; }
.status-finished { color: #1989fa; }
.status-error { color: #ff0000; }

/* 其他样式 */
.dashboard-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 16px;
  box-sizing: border-box;
}

.van-tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 999;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.console-panel {
  padding: 16px;
  margin-bottom: 12px;
  background: url('@/assets/consoleLogo.png') no-repeat center/cover;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #000;
  margin-bottom: 8px;
}

.panel-title {
  font-size: 18px;
  font-weight: bold;
}

.status-group {
  color: #000;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-label {
  color: #666;
}

.status-value {
  font-weight: 500;
}

.custom-icon {
  width: 24px;
  height: 24px;
  object-fit: contain;
}

.triangle-icon {
  width: 12px;
  height: 12px;
  margin-left: 4px;
  object-fit: contain;
}

.clickable-cell { 
  cursor: pointer;
  transition: background-color 0.2s;
}

.clickable-cell:hover {
  background-color: #f7f8fa;
}

.vehicle-section {
  padding: 1px 16px; 
  margin-bottom: 80px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.connected-wrapper {
  position: relative;
  text-align: center;
  margin-bottom: 5px; 
}

.connection-status {
  font-size: 16px;
  font-weight: bold;
  color: #1568ED;
  margin-bottom: 5px;
}

.bottom-line {
  width: 80%;
  height: 1px;
  background-color: #e5e5e5;
  margin: 0 auto;
}

.inverted-triangle {
  width: 100%;
  display: flex;
  justify-content: center;
  margin: 0 auto;
  margin-top: -1px;
}

.triangle-img {
  width: 120px;
  height: 40px;
  object-fit: contain;
}

.vehicle-cards {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-top: 8px; 
}

.confirm-dialog {
  --van-dialog-width: 80%;
  --van-dialog-border-radius: 12px;
}

.confirm-content {
  padding: 20px;
  text-align: center;
}

.confirm-header { margin-bottom: 16px; }
.confirm-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.confirm-body {
  margin-bottom: 24px;
  font-size: 15px;
  color: #666;
  line-height: 1.5;
}

.confirm-time {
  font-size: 16px;
  font-weight: bold;
  color: #1568ED;
  margin-top: 8px;
}

.confirm-footer {
  display: flex;
  justify-content: space-between;
  gap: 16px;
}

.cancel-btn {
  flex: 1;
  background-color: #f5f5f5;
  color: #333;
  border: none;
}

.confirm-btn {
  flex: 1;
  background-color: #1568ED;
}

@media (min-width: 768px) {
  .dashboard-container {
    max-width: 768px;
    margin: 0 auto;
  }
  
  .vehicle-cards {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>